#include<pthread.h>
#include<stdio.h>
#include<unistd.h>

#define NUM 5//创建的线程数目
#define TICKETS 50//初始票数

int ticket = TICKETS;

//初始化锁
pthread_mutex_t mutex = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;

//初始化线程执行的方法
void* Task(void* arg)
{
    //抢票
    while(ticket > 0)
    {
        //加锁
        pthread_mutex_lock(&mutex);
        if(ticket > 0)
        {
            ticket--;
            printf("%d get a ticket..leave: %-4d\n", arg, ticket);
        }
        //解锁
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }

    //线程终止
    pthread_exit((void*) 0);
}

int main()
{
    //创建NUM个线程
    pthread_t id[6];
    for(int i = 1;i<=NUM;i++)
    {
        pthread_create(&(id[i]),nullptr,Task,(void*)i);
    }

    //等待线程
    for(int i = 1;i<=NUM;i++)
    {
        pthread_join(id[i],nullptr);
    }
    //销毁锁
    pthread_mutex_destroy(&mutex);

    return 0;
}